window.markets = null;

$(function() {
    FastClick.attach(document.body);

    load();

    detect();

    $('header .btn').on('click', onInBasket);
    $('header .image').css({ 'background-image': g_image(decodeURIComponent(gutils.getParameter('name'))) });
}());

/**加载数据*/
function load() {
    gloading.start();
    ghttp.get('/commodity/' + window.cid + '/type/' + window.typeId + '/data', { name: window.name }, function(resp) {
        if(!resp.success) {
            gloading.stop();
            return;
        }
        // 获取菜场
        gmarket.get(function(markets) {
            window.markets = markets;

            render(resp.result);
            gloading.stop();
        }, true);
    });
}

/**检查菜是否在菜篮里*/
function detect() {
    if(gcommon.uid()) {
        ghttp.get('/personal/basket/user/' + gcommon.uid() + '/type/1/sourceId/' + window.cid, null, function(resp) {
            if(resp.success) {
                var $btn = $('header .btn');
                if(resp.result && resp.result.length > 0) {
                    // 已在菜篮
                    $btn.addClass('active');
                    $btn.text('移出菜篮');
                }
            }
        });
    }
}

function render(data) {
    renderPrices(data.prices);
    renderMenus(data.menus);

    $('.page-commodity-detail').show();
}

function renderPriceItem(item, isLowest) {
    var $prices = $('.prices ul');
    var $item = $($('#market-item-tpl').html());
    var market = getMarketById(item.marketId);

    if(market) {
        $item.find('a').attr('href','/market/'+item.marketId);
        $item.find('.name').text(market.marketName.replace('上海市普陀区', ''));
        $item.find('.price').text(item.price);
        $item.find('.price').text(item.price);

        $item.find('.distance').text(market.distance);
        if(market.isYc) { // 诚信
            $item.find('.yc').show();
        }
        if(isLowest) {
            $item.find('.low').show();
        }
        $prices.append($item);
    }
}

function renderPrices(prices) {
    var lowestPrice = 10000;
    var lowestIndex = 0;

    var allM = [];
    window.markets.forEach(function(market) {
        var item = getPriceByMarketId(prices, market.marketId);
        if(item) {
            allM.push(item);
        }
    });

    for(var i=0; i<allM.length; i++) {
        var item = allM[i];
        var p = item.price.split('元／')[0]*1;

        if(p !== 0) {
            if(p < lowestPrice) {
                lowestPrice = p;
                lowestIndex = i;
            }
        }
    }

    // 最低价
    renderPriceItem(allM[lowestIndex], true);
    // 距离排序
    window.markets.forEach(function(market, index) {
        if(index !== lowestIndex) {
            var item = getPriceByMarketId(prices, market.marketId);
            if(item) {
                renderPriceItem(item);
            }
        }
    });

}

function renderMenus(items) {
    if(items.length === 0) {
        $('.menus').hide();
        $('.page-commodity-detail').css({ 'padding-bottom':0,'margin-bottom':'60px' });
        return;
    }
    var $menus = $('.menus ul');
    items.forEach(function(item, i) {
        var $el = $($('#menu-item-tpl').html());
        $el.find('a').attr('href','/menu/'+item.id);
        $el.find('img').attr('src', item.thumbnail);
        // $el.find('.image').css({ 'background-image': 'url(' + item.thumbnail + ')' });
        $el.find('.explain .name').text(item.title);
        $el.find('.visible .num').text(item.viewCount);
        $el.find('.love .num').text(item.praiseCount);
        $menus.append($el);
    });
}

/**
 * 通过菜场ID获取菜场
 */
function getMarketById(marketId) {
    var result;
    for(var i=0; i<window.markets.length; i++) {
        if(window.markets[i].marketId == marketId) {
            result = window.markets[i];
            break;
        }
    }
    return result;
}

function getPriceByMarketId(prices, marketId) {
    var result;
    for(var i=0; i<prices.length; i++) {
        if(prices[i].marketId === marketId) {
            result = prices[i];
            break;
        }
    }
    return result;
}

/**
 * 添加到篮子
 */
function onInBasket() {
    var $btn = $('header .btn');

    gloading.start();
    ghttp.post('/personal/basket', {
        uid: gcommon.uid(),
        type: 1,
        sid: window.cid,
        name: window.name,
        extra: window.typeId + ',' + window.average
    }, function(resp) {
        if(!resp.success) {
            gloading.stop();
            return;
        }

        var count = 0;
        if($btn.hasClass('active')) {
            $btn.removeClass('active');
            $btn.text('扔进菜篮');

            count = localStorage.getItem('local-basket-count') || 0;
            if(count > 0) {
                localStorage.setItem('local-basket-count', count*1-1);
                if(count*1-1 === 0) {
                    $('.badget').hide();
                } else {
                    $('.badget').text(count*1-1).show();
                }
            }
        } else {
            $btn.addClass('active');
            $btn.text('移出菜篮');

            count = localStorage.getItem('local-basket-count') || 0;
            localStorage.setItem('local-basket-count', count*1+1);
            $('.badget').text(count*1+1).show();
        }

        gloading.stop();
    });
}